package com.glsc.ngateway.opmanage.service.other;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.base.domain.mysql.gateway.other.TradeAccountFurture;
import com.glsc.ngateway.common.base.domain.mysql.gateway.other.TradeAccountOwnFund;
import com.glsc.ngateway.common.base.domain.mysql.gateway.other.TradeAccountSaleFund;
import com.glsc.ngateway.common.base.domain.mysql.gateway.other.TradeAccountShareHolder;
import com.glsc.ngateway.common.base.domain.oracle.ecology.HrmdepartmentSimple;
import com.glsc.ngateway.common.base.domain.oracle.ecology.JYDYTZZB;
import com.glsc.ngateway.common.base.domain.oracle.ecology.VHrmResource;
import com.glsc.ngateway.common.base.repo.mysql.gateway.other.TradeAccountFurtureRepository;
import com.glsc.ngateway.common.base.repo.mysql.gateway.other.TradeAccountOwnFundRepository;
import com.glsc.ngateway.common.base.repo.mysql.gateway.other.TradeAccountSaleFundRepository;
import com.glsc.ngateway.common.base.repo.mysql.gateway.other.TradeAccountShareHolderRepository;
import com.glsc.ngateway.common.base.repo.oracle.ecology.JYDYTZZBRepository;
import com.glsc.ngateway.common.base.repo.oracle.ecology.VHrmresourceRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;


@Service
public class TradeAccountService {

    Logger logger = LoggerFactory.getLogger(TradeAccountService.class);

    @Resource
    private TradeAccountShareHolderRepository tradeAccountShareHolderRepository;

    @Resource
    private TradeAccountOwnFundRepository tradeAccountOwnFundRepository;

    @Resource
    private TradeAccountSaleFundRepository tradeAccountSaleFundRepository;

    @Resource
    private TradeAccountFurtureRepository tradeAccountFurtureRepository;

    @Resource
    private JYDYTZZBRepository jYDYTZZBRepository;

    @Resource
    private VHrmresourceRepository vHrmresourceRepository;

    @Resource
    private com.glsc.ngateway.common.base.repo.oracle.ecology.HrmdepartmentSimpleRepository hrmdepartmentSimpleRepository;


    private static final Integer SHARE_HOLDER=0;
    private static final Integer OWN_FUND=1;
    private static final Integer SALE_FUND=2;
    private static final Integer FURTURE=3;

    private static final Integer DATA_STATUS_DEL = 1;//删除

    public Object search(Object paramsObj) {
        JSONObject objParmams = JSONObject.parseObject(JSONObject.toJSONString(paramsObj)).entrySet().stream()
                .filter(entry -> !entry.getValue().toString().isEmpty())
                .collect(JSONObject::new, (obj, entry) -> obj.put(entry.getKey(), entry.getValue()), JSONObject::putAll);

        if (StrUtil.isEmpty(objParmams.getString("orderByDirection"))){
            objParmams.put("orderByDirection","DESC");
        }
        if (StrUtil.isEmpty(objParmams.getString("orderByField"))){
            objParmams.put("orderByField","id");
        }
        Sort sort = Sort.by(Sort.Direction.fromString(objParmams.getString("orderByDirection")), objParmams.getString("orderByField"));

        Pageable pageable = PageRequest.of(objParmams.getInteger("pageNo")- 1, objParmams.getInteger("pageSize"),sort);

        int accountTypeParams = objParmams.getInteger("accountTypeParams");

        if (SHARE_HOLDER == accountTypeParams){
            TradeAccountShareHolder paramSearchDto = JSONObject.parseObject(JSONObject.toJSONString(paramsObj),TradeAccountShareHolder.class);
            Page<TradeAccountShareHolder> result = tradeAccountShareHolderRepository.searchByParam(pageable,paramSearchDto);
            //修正数据：交易单元
            result.getContent().forEach(t->{
                if(Objects.nonNull(t.getTradUnit()) && Objects.isNull(t.getTradUnitNum())){
                    t.setTradUnitNum(this.getDictJYDYH(t.getTradUnit()));
                    tradeAccountShareHolderRepository.save(t);
                }
            });
            return  result;
        } else if (OWN_FUND == accountTypeParams){
            TradeAccountOwnFund paramSearchDto = JSONObject.parseObject(JSONObject.toJSONString(paramsObj),TradeAccountOwnFund.class);
            Page<TradeAccountOwnFund> result = tradeAccountOwnFundRepository.searchByParam(pageable,paramSearchDto);
            return  result;
        } else if (SALE_FUND == accountTypeParams){
            TradeAccountSaleFund paramSearchDto = JSONObject.parseObject(JSONObject.toJSONString(paramsObj),TradeAccountSaleFund.class);
            Page<TradeAccountSaleFund> result = tradeAccountSaleFundRepository.searchByParam(pageable,paramSearchDto);
            return  result;
        } else if (FURTURE == accountTypeParams){
            TradeAccountFurture paramSearchDto = JSONObject.parseObject(JSONObject.toJSONString(paramsObj),TradeAccountFurture.class);
            Page<TradeAccountFurture> result = tradeAccountFurtureRepository.searchByParam(pageable,paramSearchDto);
            return  result;
        }

        return null;

    }

    /**
     * 修改股东
     * @param tradeAccountShareHolder
     */
    public void updateShareHolder(TradeAccountShareHolder tradeAccountShareHolder) {
        tradeAccountShareHolder.setTradUnitNum(this.getDictJYDYH(tradeAccountShareHolder.getTradUnit()));
        tradeAccountShareHolderRepository.save(tradeAccountShareHolder);
    }

    @Cacheable(cacheNames = "getDictJYDY#600")
    public List<JYDYTZZB> getDictJYDY() {
        return jYDYTZZBRepository.findAll();
    }

    @Cacheable(cacheNames = "getDictJYDYH#600")
    public String getDictJYDYH(Integer tradUnit) {
        if(Objects.isNull(tradUnit)){
            return null;
        }
        Optional<JYDYTZZB> jydy = jYDYTZZBRepository.findById(tradUnit);
        return jydy.map(JYDYTZZB::getJYDYH).orElse(null);
    }

    public void updateOwnFund(TradeAccountOwnFund tradeAccountOwnFund) {
        tradeAccountOwnFundRepository.save(tradeAccountOwnFund);
    }

    public void updateSaleFund(TradeAccountSaleFund tradeAccountSaleFund) {
        tradeAccountSaleFundRepository.save(tradeAccountSaleFund);
    }

    public void updateFurture(TradeAccountFurture tradeAccountFurture) {
        tradeAccountFurtureRepository.save(tradeAccountFurture);
    }

    public void deleteShareHolder(TradeAccountShareHolder tradeAccountShareHolder) {
        Optional<TradeAccountShareHolder> optional = tradeAccountShareHolderRepository.findById(tradeAccountShareHolder.getId());
        if (optional.isPresent()) {
            TradeAccountShareHolder bean = optional.get();
            bean.setDataStatus(DATA_STATUS_DEL);
            tradeAccountShareHolderRepository.save(bean);
        } else {
            throw new IllegalArgumentException("删除记录不存在");
        }
    }

    public void deleteOwnFund(TradeAccountOwnFund tradeAccountOwnFund) {
        Optional<TradeAccountOwnFund> optional = tradeAccountOwnFundRepository.findById(tradeAccountOwnFund.getId());
        if (optional.isPresent()) {
            TradeAccountOwnFund bean = optional.get();
            bean.setDataStatus(DATA_STATUS_DEL);
            tradeAccountOwnFundRepository.save(bean);
        } else {
            throw new IllegalArgumentException("删除记录不存在");
        }
    }

    public void deleteSaleFund(TradeAccountSaleFund tradeAccountSaleFund) {
        Optional<TradeAccountSaleFund> optional = tradeAccountSaleFundRepository.findById(tradeAccountSaleFund.getId());
        if (optional.isPresent()) {
            TradeAccountSaleFund bean = optional.get();
            bean.setDataStatus(DATA_STATUS_DEL);
            tradeAccountSaleFundRepository.save(bean);
        } else {
            throw new IllegalArgumentException("删除记录不存在");
        }
    }

    public void deleteFurture(TradeAccountFurture tradeAccountFurture) {
        Optional<TradeAccountFurture> optional = tradeAccountFurtureRepository.findById(tradeAccountFurture.getId());
        if (optional.isPresent()) {
            TradeAccountFurture bean = optional.get();
            bean.setDataStatus(DATA_STATUS_DEL);
            tradeAccountFurtureRepository.save(bean);
        } else {
            throw new IllegalArgumentException("删除记录不存在");
        }
    }

    /**
     * 默认600秒缓存更新
     * @return
     */
    //Status状态字典：0：试用  1：正式  2：临时  3：试用延期  4：解聘  5：离职  6：退休  7：无效
    private static List<String> ALIVE_STATUS = List.of("0", "1", "2", "3");
    @Cacheable(cacheNames = "getDictHRM#600")
    public List<VHrmResource> getDictHRM() {
        return vHrmresourceRepository.findAllByOaStatusIn(ALIVE_STATUS);
    }

    /**
     * 默认600秒缓存更新
     * @return
     */
    @Cacheable(cacheNames = "getDictDEPT#600")
    public List<HrmdepartmentSimple> getDictDEPT() {
        return hrmdepartmentSimpleRepository.findAll();
    }
}
